﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteFramework.Server
{
    public sealed class ApplicationSetting
    {
        private static string configurationFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

        #region 读配置...

        //...
        public static int ReadAppSetting(string key, int defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToInt32(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        //...
        public static double ReadAppSetting(string key, double defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDouble(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static float ReadAppSetting(string key, float defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToSingle(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static decimal ReadAppSetting(string key, decimal defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDecimal(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static DateTime ReadAppSetting(string key, DateTime defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDateTime(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 读取应用程序的配置信息
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string ReadAppSetting(string key, string defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            return (String.IsNullOrEmpty(setting)) ? defaultValue : setting;
        }

        /// <summary>
        /// 读取应用程序的配置信息
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static bool ReadAppSetting(string key, bool defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            return (String.IsNullOrEmpty(setting)) ? defaultValue : (string.Compare(setting, Boolean.TrueString, true) == 0);
        }

        #endregion 读配置...

        #region 写配置
        public static void WriteAppSetting(string key, object value)
        {
            Configuration configuration = OpenConfiguration();

            AppSettingsSection appSection = configuration.AppSettings;
            if (value == null)
                appSection.Settings.Remove(key);
            else
            {
                if (appSection.Settings[key] != null)
                    appSection.Settings[key].Value = (value.ToString());
                else
                    appSection.Settings.Add(key, value.ToString());
            }

            appSection.SectionInformation.ForceSave = true;
            configuration.Save();
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="all">false只，结果将不包含AppSetting中“defaultConnectionStringName”所设定的值（未指定时，默认为“default”）</param>
        /// <returns></returns>
        public static string[] GetConnectionStringNames(bool all = false)
        {
            string defName = ReadAppSetting("defaultConnectionStringName", "default");

            Configuration configuration = OpenConfiguration();
            ConnectionStringSettingsCollection cssc = configuration.ConnectionStrings.ConnectionStrings;

            List<string> list = new List<string>();

            for (int i = 0; i < cssc.Count; i++)
            {
                if (all || String.Compare(cssc[i].Name, defName, true) != 0)
                    list.Add(cssc[i].Name);
            }

            return list.ToArray();
        }
        /// <summary>
        /// 获取默认连接字符串配置名称。读取AppSetting中“defaultConnectionStringName”所设定的值（未指定时，默认为“default”）
        /// </summary>
        /// <returns></returns>
        public static string GetDefaultConnectionStringName()
        {
            return ReadAppSetting("defaultConnectionStringName", "default");
        }
        /// <summary>
        /// 获取默认连接字符串配置所使用的Sql方言。读取AppSetting中“defaultConnectionDialect”所设定的值（未指定时，默认为“Dialect.MsSqlDialect, Haode.Dialect.MsSqlDialect”）
        /// </summary>
        /// <returns></returns>
        public static string GetDefaultConnectionDialect()
        {
            return ReadAppSetting("defaultConnectionDialect", "Dialect.MsSqlDialect, Haode.Dialect.MsSqlDialect");
        }

        public static ConnectionStringSettings GetConnectionStringSettings(string name)
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings[name];
        }

        #region private

        private static Configuration OpenConfiguration()
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configurationFileName;

            return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        }

        #endregion
    }
}